from django import forms
from django.core.exceptions import ValidationError
from django.shortcuts import get_object_or_404
from django.utils.translation import gettext_lazy as _
from .models import BookInstance, Author
import datetime

class RenewBookForm(forms.Form):
    """续借图书的表单"""
    renewal_date = forms.DateField(
        help_text="输入续借日期（最多可续借4周）",
        widget=forms.DateInput(attrs={'type': 'date'})
    )

    def __init__(self, *args, bookinstance_id=None, **kwargs):
        self.bookinstance_id = bookinstance_id
        super().__init__(*args, **kwargs)
        # 这里可以根据 bookinstance_id 做一些额外的初始化逻辑，比如从数据库获取实例
        if bookinstance_id:
            self.book_instance = get_object_or_404(BookInstance, pk=bookinstance_id)


    def clean_renewal_date(self):
        """验证续借日期是否合法"""
        data = self.cleaned_data['renewal_date']

        # 检查日期是否在当前日期之后
        if data < datetime.date.today():
            raise ValidationError("续借日期不能早于当前日期")

        # 检查日期是否在允许的续借期限内（4周后）
        if data > datetime.date.today() + datetime.timedelta(weeks=4):
            raise ValidationError("续借日期不能超过4周后")

        return data

class AuthorForm(forms.ModelForm):
    """作者表单（用于创建和更新）"""

    class Meta:
        model = Author
        fields = ['first_name', 'last_name', 'date_of_birth', 'date_of_death']
        widgets = {
            'date_of_birth': forms.DateInput(attrs={'type': 'date'}),
            'date_of_death': forms.DateInput(attrs={'type': 'date'}),
        }

    def clean_date_of_death(self):
        data = self.cleaned_data.get('date_of_death')
        birth_date = self.cleaned_data.get('date_of_birth')

        if birth_date and data and data < birth_date:
            raise ValidationError(_("死亡日期不能早于出生日期"))

        return data